var myObj = {};
function getDeliver(dom){
	if($(dom).val()==1){
		$(".deliverwl").hide();
        $(".deliverdd").hide();
		$(".deliverps").show();
	}else if($(dom).val()==0){
        $(".deliverps").hide();
        $(".deliverdd").hide();
		$(".deliverwl").show();
	}else {
        $(".deliverwl").hide();
        $(".deliverps").hide();
        $(".deliverdd").show();
    }

}

function getDeliverw(dom){
    if($(dom).val()==1){
        $('.deliverpsw').hide();
    }else if($(dom).val()==0){
        $('.deliverpsw').show();
    }
}

function dochang(num){
	if(num=='2'){
		$("#status1").val("2");
		document.getElementById("doQuery").click();
	}
	if(num=='3'){
		$("#status1").val("3");
		document.getElementById("doQuery").click();
	}
	if(num=='4'){
		$("#status1").val("4");
		document.getElementById("doQuery").click();
	}
	if(num=='7'){
		$("#status1").val("7");
		document.getElementById("doQuery").click();
	}
	if(num=='8'){
		$("#status1").val("8");
		document.getElementById("doQuery").click();
	}
	if(num==null){
		$("#status1").val("");
		document.getElementById("doQuery").click();
	}
}

function dochang1(num){
	if(num=='2'){
		$("#status1").val("2");
		document.getElementById("doQuery1").click();
	}
	/*if(num=='0'){
		$("#status1").val("0");
		document.getElementById("doQuery1").click();
	}*/
	if(num=='4'){
		$("#status1").val("4");
		document.getElementById("doQuery1").click();
	}
	if(num=='1'){
		$("#status1").val("1");
		document.getElementById("doQuery1").click();
	}
	if(num==null){
		$("#status1").val("");
		document.getElementById("doQuery1").click();
	}
}

// 发货
function shipments(dom){
	var oData_arr = $('#table_order').DataTable().rows(dom.parents("tr")).data(); // 操作行对象
	var _id = oData_arr[0].id;
	window.location.href="/p/user/order/shipments?id="+ encodeURIComponent(_id);
}

// 审核
function audit(dom){
	var oData_arr = $('#table_order1').DataTable().rows(dom.parents("tr")).data(); // 操作行对象
	var _id = oData_arr[0].id;
	window.location.href="/p/user/refundOrder/audit?id="+ encodeURIComponent(_id);
}

//退款
function refund(dom){
	var oData_arr = $('#table_order1').DataTable().rows(dom.parents("tr")).data(); // 操作行对象
	var _id = oData_arr[0].id;
	$.ajax({
		url : '/a/user/refundOrder/order2',
		type : 'post',
		dataType : 'json',
		contentType:"application/json; charset=utf-8",
		async: false,
		data : JSON.stringify({ id: _id }),
	}).done(function(r) {
		$("#mytag").val(r.data[0][0]);
		var html="";
		if(r.data[1].length==3){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][0]+"\"><img src=\""+r.data[1][0]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][1]+"\"><img src=\""+r.data[1][1]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][2]+"\"><img src=\""+r.data[1][2]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		if(r.data[1].length==2){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][0]+"\"><img src=\"$"+r.data[1][0]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][1]+"\"><img src=\"$"+r.data[1][1]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		if(r.data[1].length==1){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][2]+"\"><img src=\"$"+r.data[1][2]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		$("#shDetail").html();
		$("#shDetail").html(
				"<div class=\"col-xs-3 text-center\">申请时间</div><div class=\"col-xs-8\">"+r.data[0][1]+"</div>" +
				"<div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">商品状态</div>"+
				"<div class=\"col-xs-8\">"+r.data[0][2]+"</div><div class=\"col-xs-12\" style=\"height:10px\"></div>" +
				"<div class=\"col-xs-3 text-center\">售后原因</div><div class=\"col-xs-8\">"+r.data[0][3]+"</div>" +
				"<div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">"+r.data[0][4]+"</div>" +
				"<div class=\"col-xs-8\" style=\"color:red\">"+r.data[0][5]+"</div><div class=\"col-xs-12\" style=\"height:10px\"></div>" +html
		);
		
	});
	/*$("a[rel=example_group]").fancybox({
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'titlePosition': 'over'
	}); */
}

// 退款完成
function endRefund(dom){
	var oData_arr = $('#table_order1').DataTable().rows(dom.parents("tr")).data(); // 操作行对象
	var _id = oData_arr[0].id;
	$.ajax({
		url : '/a/user/refundOrder/order2',
		type : 'post',
		dataType : 'json',
		contentType:"application/json; charset=utf-8",
		async: false,
		data : JSON.stringify({ id: _id }),
	}).done(function(r) {
		var html="";
		var tem="<div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">处理结果</div><div class=\"col-xs-8\">" +
		r.data[0][6]+"</div><div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">处理时间</div>" +
		"<div class=\"col-xs-8\">"+r.data[0][7]+"</div>";

		if(r.data[1].length==3){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][0]+"\"><img src=\""+r.data[1][0]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][1]+"\"><img src=\""+r.data[1][1]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][2]+"\"><img src=\""+r.data[1][2]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		if(r.data[1].length==2){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\"  href=\""+r.data[1][0]+"\"><img src=\"$"+r.data[1][0]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][1]+"\"><img src=\"$"+r.data[1][1]+"\"  style=\"margin-left: 3%\" width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		if(r.data[1].length==1){
			html="<div class=\"col-xs-3 text-center\">售后凭证</div><div class=\"col-xs-8\"><span>" +
			"<a rel=\"example_group\" target=\"_blank\" href=\""+r.data[1][2]+"\"><img src=\"$"+r.data[1][2]+"\"   width=\"81px\" height=\"81px\"/></a>" +
			"</span></div>";
		}
		$("#shDetail1").html();
		$("#shDetail1").html(
				"<div class=\"col-xs-3 text-center\">申请时间</div><div class=\"col-xs-8\">"+r.data[0][1]+"</div>" +
				"<div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">商品状态</div>"+
				"<div class=\"col-xs-8\">"+r.data[0][2]+"</div><div class=\"col-xs-12\" style=\"height:10px\"></div>" +
				"<div class=\"col-xs-3 text-center\">售后原因</div><div class=\"col-xs-8\">"+r.data[0][3]+"</div>" +
				"<div class=\"col-xs-12\" style=\"height:10px\"></div><div class=\"col-xs-3 text-center\">"+r.data[0][4]+"</div>" +
				"<div class=\"col-xs-8\" style=\"color:red\">"+r.data[0][5]+"</div><div class=\"col-xs-12\" style=\"height:10px\"></div>" +html+tem
		);
	});
	
/*	$("a[rel=example_group]").fancybox({
		'transitionIn': 'elastic',
		'transitionOut': 'elastic',
		'titlePosition': 'over'
	});*/
}

// 订单数据模型
var orderManage = function() {

    var datalist_url = $('.datalist_url').val();
    var view_url = $('.view_url').val();
    var table = $('#table_order');

    var init_datepicker = function () {
        // 开始时间
        $('#begin_time').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            endDate : new Date()
        }).on('changeDate',function(e){
            var startTime = e.date;
            $('#end_time').datepicker('setStartDate', startTime);
        });
        // 结束时间：
        $('#end_time').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            endDate : new Date()
        }).on('changeDate',function(e){
            var endTime = e.date;
            $('#begin_time').datepicker('setEndDate', endTime);
        });
    };

    var _init = function() {
        var storeId = $('#storeId').find("option:selected").val();
        var tableUnit = table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
                url: datalist_url,
                data: {'storeId': storeId}
            },
            // id, openId, name, gender, dateOfBirth, mobile, nickName,
            // avatarUrl, integral, createDate,
            // updateDate, createOper, updateOper, balance, wxCode, isMember,
            // source, status, tenantId
            "autoWidth": false,
            "columns": [
                {
                    "width": "9%",
                    "data": "productImg",
                    "render": function(data, type, row, meta) {
                        return '<img src="'+data+'" alt="" style="width: 70px;height: 70px;" />';
                    }
                },
                {
                    "width": "12%",
                    "data":"orderNO",
                },
                {
                    "width": "9%",
                    "data":"total_count"
                },
                {
                    "width": "9%",
                    "data":"payMethod",
                    "render":function(data, type, row, meta) {
                        if(data == 0){
                            return '微信支付';
                        }else{
                            return '余额支付';
                        }
                    }
                },
                {
                    "width": "9%",
                    "data": "total",
                    "render":function(data, type, row, meta) {
                        //row.linkType
                        if(data == '0'){
                            return '0';
                        }else{
                            return data / 100;
                        }
                    }
                },
                {
                    "width": "12%",
                    "data": "userName"
                },
                {
                    "width": "12%",
                    "data": "userPhone"
                },
                /*{
                    "width": "12%",// 买家
                    "data": "id",
                    "render": function(data, type, row, meta) {
                        var val="--";
                        if(data!=null&&data!=''){
                            $.ajax({
                                url : '/a/user/order/user',
                                type : 'post',
                                dataType : 'json',
                                contentType:"application/json; charset=utf-8",
                                async: false,
                                data : JSON.stringify({ id: data }),
                            }).done(function(r) {
                                if (r.status === '1') {
                                    if(null != r.data){
                                        if(null==r.data.mobile){
                                            r.data.mobile="--";
                                        }
                                        val=r.data.mobile;// r.data.属性
                                    } else if (r.status == '2') {

                                    }
                                }
                            });
                            return val;
                        }else{
                            return "--";
                        }
                    }
                },*/
                {
                    "width": "8%",
                    "data": "create_time",
                    "render":function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD HH:mm:ss');
                    }
                },
                {
                    "width": "8%",
                    "data": "linkType",
                    "render":function(data, type, row, meta) {
                        var val = "--";
                        switch (data){
                            case 0:
                                val = '普通订单';
                                break;
                            case 1:
                                val = '团购订单';
                                break;
                            default:
                                val = "积分订单";
                                break;
                        }
                        return val;
                    }
                },
                {
                    "width": "10%",
                    "data": "status",
                    "render": function(data, type, row, meta) {
                        var val = "--";
                        switch (data) {
                            case 1:
                                val = "待付款";
                                break;
                            case 2:
                                val = "待发货";
                                break;
                            case 3:
                                val = "待收货";
                                break;
                            case 4:
                                val = "已完成";
                                break;
                            case 5:
                                val = "已失效";
                                break;
                            case 6:
                                val = "售后";
                                break;
                            case 7:
                                val = "已消费";
                                break;
                            case 8:
                                val = "未消费";
                                break;
                            case 9:
                                val = "拼团中";
                                break;
                            case 10:
                                val = "同意售后退款";
                                break;
                            default:
                                val = "拒绝售后退款";
                                break;
                        }
                        return val;
                    }
                },
                {
                    "width": "10%",
                    "data": "null",
                    "render": function(data, type, row, meta) {
                        return '<a href="'+view_url+'?linkType='+row.linkType+'&id='+row.id+'" class="btn btn-info">详情</a>';
                    }
                }
            ],
            "language": {
                /*"lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."*/
                url: '/public/static/assets/pages/Chinese.json'
            },
            "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
            "pageLength": 10,
            "scrollX":"",
            "destroy": false,
            "stateSave": false, // 状态保存
            "stateSaveParams": function (settings, data) {
                var search = data.search.search;
                if(search){
                    var arr = $.parseJSON(search);
                    for(var key in arr){
                        if(key != 'storeId'){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                }
            },
            "order": [
                [7, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0,1,2,4,5,6,9]
            }
            /*
             * ,{ "targets": 2, "render": function(data, type,
             * row, meta) { var val=data;
             * if(data!=null&&data!=''){ $.ajax({ url :
             * '/a/biz/alevel/obj', type : 'post', dataType :
             * 'json', contentType:"application/json;
             * charset=utf-8", async: false, data :
             * JSON.stringify({ id: data }), }).done(function(r) {
             * if (r.status === '1') { val=r.data.name;
             *  } else if (r.status === '2') { } }); return val;
             * }else return ""; } }, { "targets": 6, "render":
             * function(data, type, row, meta) { if(data=='0'){
             * return "停用"; }else{ return "正常"; } } } ,{
             * "targets": 7, "render": function(data, type, row,
             * meta) { var val=data; if(data!=null&&data!=''){
             *
             * $.ajax({ url : '/a/sys/operator', type : 'post',
             * dataType : 'json', contentType:"application/json;
             * charset=utf-8", async: false, data :
             * JSON.stringify({ id: data }), }).done(function(r) {
             * if (r.status === '1') { val=r.data.name;
             *  } else if (r.status === '2') { } }); return val;
             * }else return ""; } }, { "targets": 8,
             *  }
             */
            ],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnInitComplete": function() {
                //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
            }
        });

        Date.prototype.pattern=function(fmt) {
            var o = {
                "M+" : this.getMonth()+1, // 月份
                "d+" : this.getDate(), // 日
                "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, // 小时
                "H+" : this.getHours(), // 小时
                "m+" : this.getMinutes(), // 分
                "s+" : this.getSeconds(), // 秒
                "q+" : Math.floor((this.getMonth()+3)/3), // 季度
                "S" : this.getMilliseconds() // 毫秒
            };
            var week = {
                "0" : "/u65e5",
                "1" : "/u4e00",
                "2" : "/u4e8c",
                "3" : "/u4e09",
                "4" : "/u56db",
                "5" : "/u4e94",
                "6" : "/u516d"
            };
            if(/(y+)/.test(fmt)){
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            }
            if(/(E+)/.test(fmt)){
                fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
            }
            for(var k in o){
                if(new RegExp("("+ k +")").test(fmt)){
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                }
            }
            return fmt;
        }
        // var date=new Date($("#brithday").val()==""?new
        // Date():$("#brithday").val());
        // $("#brithday").val(date.pattern("MM/dd/yyyy"));
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    return {
        init: function() {
            init_datepicker();
            _init();

            this.onEvent();
        },
        onEvent: function () {
            // 切换门店
            $('#storeId').on('change', function(){
                var storeId = $(this).val();
                var linkType = $('#linkType').val();
                var table = $('#table_order');
                tableSearch(table, {'storeId':storeId, 'linkType':linkType});
            });

            // 普通订单/拼团
            $('#linkType').on('change', function(){
                var linkType = $(this).val();
                var storeId = $('#storeId').val();
                var table_refund = $('#table_order');
                tableSearch(table_refund, {'linkType':linkType, 'storeId':storeId});
            });

            // 动态查询
            $('#doQuery').on('click', function(event){
                var storeId = $("select[name='storeId']").val();
                var linkType = $("select[name='linkType']").val();
                var status = $("select[name='status']").val();
                var orderNO = $("input[name='orderNO']").val();
                var begin_time = $("input[name='begin_time']").val();
                var end_time = $("input[name='end_time']").val();
                var params = {
                    "storeId" : storeId,
                    "linkType" : linkType,
                    "status" : status,
                    "orderNO" : orderNO,
                    "begin_time" : begin_time,
                    "end_time" : end_time
                };
                var table = $('#table_order');
                tableSearch(table, params);
            });

            // 批量导出
            $('#export_csv').on('click', function(){
                var url = $(this).data('url');
                var storeId = $("select[name='storeId']").val();
                var linkType = $("select[name='linkType']").val();
                var status = $("select[name='status']").val();
                var orderNO = $("input[name='orderNO']").val();
                var begin_time = $("input[name='begin_time']").val();
                var end_time = $("input[name='end_time']").val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="storeId" value="'+storeId+'" >';
                $form += '<input name="linkType" value="'+linkType+'" >';
                $form += '<input name="status" value="'+status+'" >';
                $form += '<input name="orderNO" value="'+orderNO+'" >';
                $form += '<input name="begin_time" value="'+begin_time+'" >';
                $form += '<input name="end_time" value="'+end_time+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });
        }
    };
}();


// 售后订单数据模型
var refundManage = function() {

    var datalist_url = $('.datalist_url').val();
    var view_url = $('.view_url').val();
    var table_refund = $('#table_refund');

    var init_datepicker = function () {
        // 开始时间
        $('#begin_time').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            endDate : new Date()
        }).on('changeDate',function(e){
            var startTime = e.date;
            $('#end_time').datepicker('setStartDate', startTime);
        });
        // 结束时间：
        $('#end_time').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            endDate : new Date()
        }).on('changeDate',function(e){
            var endTime = e.date;
            $('#begin_time').datepicker('setEndDate', endTime);
        });
    };

	var _init = function() {
        var storeId = $('#storeId').find("option:selected").val();
        var tableUnit = table_refund.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
                url: datalist_url,
                data: {'storeId': storeId}
            },
            "autoWidth": false,
            "columns": [
                {
                    "width": "9%",
                    "data": "productImg",
                    "render": function(data, type, row, meta) {
                        return '<img src="'+data+'" alt="" style="width: 70px;height: 70px;" />';
                    }
                },
                {
                    "width": "12%",
                    "data":"orderNO",
                },
                {
                    "width": "9%",
                    "data": "refund_fee",
                    "render":function(data, type, row, meta) {
                        //row.linkType
                        if(data == '0'){
                            return '0';
                        }else{
                            return data / 100;
                        }
                    }
                },
                {
                    "width": "12%",
                    "data": "userPhone"
                },
                {
                    "width": "8%",
                    "data": "create_time",
                    "render":function(data, type, row, meta) {
                        return moment(data).format('YYYY-MM-DD HH:mm:ss');
                    }
                },
                {
                    "width": "10%",
                    "data": "status",
                    "render": function(data, type, row, meta) {
                        var val = "--";
                        switch (data) {
                            case 1:
                                val = "拒绝售后";
                                break;
                            case 2:
                                val = "已退款";
                                break;
                            case 3:
                                val = "删除";
                                break;
                            case 4:
                                val = "申请中";
                                break;
                            case 5:
                                val = "取消售后";
                                break;
                            default: break;
                        }
                        return val;
                    }
                },
                {
                    "width": "10%",
                    "data": "null",
                    "render": function(data, type, row, meta) {
                        return '<a href="'+view_url+'?id='+row.id+'" class="btn btn-info">详情</a>';
                    }
                }
            ],
            "language": {
                url: '/public/static/assets/pages/Chinese.json'
            },
            "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
            "pageLength": 10,
            "scrollX":"",
            "destroy": false,
            "stateSave": false,
            "stateSaveParams": function (settings, data) {
                var search = data.search.search;
                if(search){
                    var arr = $.parseJSON(search);
                    for(var key in arr){
                        if(key != 'storeId'){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                }
            },
            "order": [
                [4, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0,1,2,3,6]
            }
            ],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnInitComplete": function() {
                //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
            }
        });
	};

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

	return {
		init: function() {
            init_datepicker();
            _init();

            this.onEvent();
		},
        onEvent: function () {
            // 切换门店
            $('#storeId').on('change', function(){
                var storeId = $(this).val();
                var table_refund = $('#table_refund');
                tableSearch(table_refund, {'storeId':storeId});
            });

            // 动态查询
            $('#doQuery').on('click', function(event){
                var storeId = $("select[name='storeId']").val();
                var status = $("select[name='status']").val();
                var orderNO = $("input[name='orderNO']").val();
                var begin_time = $("input[name='begin_time']").val();
                var end_time = $("input[name='end_time']").val();
                var params = {
                    "storeId" : storeId,
                    "status" : status,
                    "orderNO" : orderNO,
                    "begin_time" : begin_time,
                    "end_time" : end_time
                };
                var table_refund = $('#table_refund');
                tableSearch(table_refund, params);
            });

            // 批量导出
            $('#refund-export_csv').on('click', function(){
                var url = $(this).data('url');
                var storeId = $("select[name='storeId']").val();
                var status = $("select[name='status']").val();
                var orderNO = $("input[name='orderNO']").val();
                var begin_time = $("input[name='begin_time']").val();
                var end_time = $("input[name='end_time']").val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="storeId" value="'+storeId+'" >';
                $form += '<input name="status" value="'+status+'" >';
                $form += '<input name="orderNO" value="'+orderNO+'" >';
                $form += '<input name="begin_time" value="'+begin_time+'" >';
                $form += '<input name="end_time" value="'+end_time+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });


            //提交售后处理
            $("#yesOrder").click(function(){
                //ajax处理  url  /a/user/refundOrder/doRefund
                var _data = $("#refund").serializeObject();
                var _id=_data.id;
                //console.log(_data.order_price);
                if(_data.actiontype == '0'){
                    if (!mdTool.validate(_data.content, 'require')) {
                        layer.msg('请输入不同意原因', {icon: 5, time: 3000});
                        return;
                    }
                    else {
                        mdTool.showMessage1('');
                        $.ajax({
                            url : '/admin/Refund/doRefund',
                            type : 'post',
                            dataType : 'json',
                            contentType:"application/json; charset=utf-8",
                            async: false,
                            data : JSON.stringify(_data),
                        }).done(function(r) {
                            if (r.status == '1') {
                                layer.msg(r.message, {icon: 6, time: 3000});
                                window.location.reload();
                            } else if (r.status == '0') {
                                layer.msg(r.message, {icon: 5, time: 3000});
                                $('#myModal2').modal('hide');
                            }
                        });
                    }
                }else{
                    if(_data.fefund_isall == 0){
                        if (!mdTool.validate(_data.refund_fee, 'require')) {
                            layer.msg('请输入一个数额', {icon: 5, time: 3000});
                            return false;
                        }
                        if (!mdTool.validate(_data.refund_fee, 'two')) {
                            layer.msg('请输入正确的数额', {icon: 5, time: 3000});
                            return false;
                        }
                        if(_data.refund_fee*100 > _data.order_price){
                            layer.msg('退款金额不能大于订单金额', {icon: 5, time: 3000});
                            return false;
                        }
                    }

                    mdTool.showMessage1('');
                    layer.open({
                        type: 1
                        ,title: "提示" //不显示标题栏   title : false/标题
                        ,closeBtn: true
                        ,area: '300px;'
                        ,shade: 0.6
                        ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
                        ,resize: false
                        ,btn: ['确定', '取消']
                        ,btnAlign: 'c'
                        ,moveType: 1 //拖拽模式，0或者1
                        ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">确定要退款给用户吗？</div>'
                        ,success: function(layero){
                            var btn = layero.find('.layui-layer-btn');
                            btn.find('.layui-layer-btn0').click(function(){

                                $.ajax({
                                    url : '/admin/Refund/doRefund',
                                    type : 'post',
                                    dataType : 'json',
                                    contentType:"application/json; charset=utf-8",
                                    async: false,
                                    data : JSON.stringify(_data),
                                }).done(function(r) {
                                    if (r.status == '1') {
                                        layer.msg(r.message, {icon: 6, time: 3000});
                                        location.reload();
                                    } else if (r.status == '0') {
                                        layer.msg(r.message, {icon: 5, time: 3000});
                                        $('#myModal2').modal('hide');
                                    }
                                });
                            });
                        }
                    });


                }
            });

            /**
             * 留言展示
             */
            $(".radios").click(function(){
                var val=$(this).val();
                if(val=="1")
                {
                    $("#money").hide();
                    $("#liuyan").show();
                }
                else
                {
                    $("#liuyan").hide();
                    $("#money").show();
                }
            });
        }
	};
}();

/*
 * $("#type1").change(function(){ var val=$("#type1").val(); if(val==='0'){
 * $("#status1").html(" <option value=''>订单状态</option><option value='1' >待付款</option><option
 * value='2' >待发货</option><option value='3' >待收货</option>" + "<option
 * value='4' >已完成</option><option value='6' >售后/退款</option><option
 * value='9'>拼团中</option>"); }else if(val==='1'){ $("#status1").html("<option
 * value=''>订单状态</option><option value='7' >已消费</option><option value='8'
 * >未消费</option><option value='6' >售后/退款</option><option value='9'>拼团中</option>");
 * 
 * }else{ $("#status1").html(" <option value=''>订单状态</option><option value='1'
 * >待付款</option><option value='2' >待发货</option><option value='3' >待收货</option>" + "<option
 * value='4' >已完成</option><option value='6' >售后/退款</option><option value='7'
 * >已消费</option><option value='8' >未消费</option><option value='9'>拼团中</option>"); }
 *  })
 */


// 取消
$('#return_add').click(function(event) {
	window.location.href="/p/user/refundOrder";
});
$('#return_add1').click(function(event) {
	window.history.back();
});
// 确定添加，添加用户数据校验
// $("#form_role_new").find('button[type=submit]').click(function() {
$("#Delivergoods").click(function() {

	var _data = $("#form_address_add").serializeObject();
	var _id=_data.id;
	if(_data.deliverMethod==1){
		//自行配送
		if (!mdTool.validate(_data.deliverUserName, 'require')) {
            layer.msg('请选择送货员', {icon: 5, time: 3000});
			return;
		}
		else {
            postDelivergoods(_data);
		}
	}else if(_data.deliverMethod == 2) {
        //提交与发送哒哒订单
        var $url = "/admin/order/queryDeliverFee";
        var orderId = _data.id;
        var storeId = _data.storeId;
        var $param = {
            id: orderId
        };

        $.ajax({
            type: 'POST',
            url: $url,
            data: $param,
            dataType: 'json',
            success: function (data) {

				if(data.status==1){
                    openSelfDialog(data);
                    function openSelfDialog(data) {
                        parent.layer.confirm(
                        	'<div style="padding: 20px; line-height: 22px; font-weight: 800;">配送方式：达达配送<br>达达运费：'+data.data.fee+'元<br/>说明：此运费由达达平台收取，确定发单后订单会下发到达达平台，配送时间由达达平台决定。</div>',
							{
                            	btn: ['确定向达达发单','再考虑一下'] //按钮
                        	},
							function(){
                        		//alert(data.data.deliveryNo)
                                $.ajax({
                                    type: 'POST',
                                    url: '/admin/order/addAfterQuery',
                                    data: {deliveryNo:data.data.deliveryNo,orderId:data.data.order_id,fee:data.data.fee,storeId:storeId},
                                    dataType: 'json',
                                    success: function (data) {
                                        if(data.status == '0'){
                                            layer.msg(data.message, {icon: 5});
                                        }else {
                                            layer.msg('发单成功', {icon: 1});
                                            //打印小票
                                            var printer_url = '/admin/PrinterConsole/printsConsole';
                                            $.ajax({
                                                url :printer_url,
                                                type : 'POST',
                                                dataType : 'json',
                                                contentType:"application/json; charset=utf-8",
                                                data : JSON.stringify({"orderId":orderId,"storeId":storeId,"businessId":null,"isauto":false,type:'达达配送'}),
                                            }).done(function(data) {
                                                if(data.status === 0) {
                                                    layer.msg(data.message, {icon: 5, time: 3000});
                                                } else if(data.status == 1){
                                                    layer.msg(data.message, {icon: 6, time: 3000});
                                                }
                                            });
                                        }
									},
                                    error: function (data) {
                                        console.log(data.msg);
                                    },
								})

                        },function(){
                                layer.msg('已经取消', {icon: 1});
                            });
					}




				}else {
				    if(data.status = 9008){
                        layer.confirm(data.message+'，需要充值吗？', {
                            btn: ['需要','不需要'] //按钮
                        }, function(){
                            window.location.href="/admin/tenant/index";
                        }, function(){
                            layer.msg('ok', {
                                time: 1000, //2s后自动关闭
                            });
                        });
                    }else {
                        layer.msg(data.message, {icon: 5, time: 3000});
                    }

				}

                console.log(JSON.stringify(data))
              //  layer.msg(data.message, {icon: 6, time: 1000});
            },
            error: function (data) {
                console.log(data.msg);
            },
        });


	}else{
		//自选物流
		if (!mdTool.validate(_data.expressName, 'require')) {
            layer.msg('请选择一个快递公司', {icon: 5, time: 3000});
			return false;
		}

		else if (!mdTool.validate(_data.expressNo, 'require')) {
            layer.msg('请输入快递单号', {icon: 5, time: 3000});
			return;
		}
        else if (!mdTool.validate(_data.expressNo, 'ecode')) {
            layer.msg('快递单号不能包含汉字', {icon: 5, time: 3000});
            return;
        }
		else {
            postDelivergoods(_data);

		}
	}
	});

function postDelivergoods($data) {
    layer.msg('提交中', {icon: 6, time: 2000});
    $.ajax({
        type: 'POST',
        url: '/admin/Order/DoDelivergoods',
        data: JSON.stringify($data),
        dataType: 'json',
        contentType:"application/json; charset=utf-8",
        success: function (data) {

            if(data.status == '1'){
                layer.msg(data.data.message, {icon: 6, time: 3000});
                window.history.back(-1);
            }else {
                layer.msg(data.message, {icon: 5, time: 3000});
            }

            console.log(JSON.stringify(data))
            //  layer.msg(data.message, {icon: 6, time: 1000});
        },
        error: function (data) {
            console.log(data.msg);
        },
    });
}
$("#sava_add1").click(function() {
	var _data = $("#form_refund_add").serializeObject();
	if(_data.status == 1){
		if (!mdTool.validate(_data.content, 'require')) {
			mdTool.showMessage1('请输入处理说明');
			return;
		}
		else {
			mdTool.showMessage1('');
			$("#form_refund_add").submit();
		}
	}else{
		mdTool.showMessage1('');
		$("#form_refund_add").submit();
	}
});

$("#sava_add2").click(function() {
	var _data = $("#form_refund_yes").serializeObject();
	var _id=_data.id;
	/*
	 * var _total=_data.total; if(null != _total && 0!= _total.trim().length){
	 * if (isNaN(_total)) { alert("请输入数字"); return false; } }
	 */
	bootbox.dialog({
		message : "退款前请仔细确认",
		title : "提示",
		buttons : {

			success : {
				label : "确定",
				className : "btn green",
				callback : function() {

					$.ajax({
						url: '/a/user/refundOrder/doRefund',
						type: 'post',
						dataType: 'json',
						contentType:"application/json; charset=utf-8",
						data: JSON.stringify({
							id : _id/* ,total : _total */
						}),
					})
					.done(function(data) {
						if(data.status ==='1'){
							alert('退款成功');
							$("#sava_add2").hide();
							$("#return_add").text("返回");
						}else {
							alert(data.message);
						}

					});
				}
			},cancel : {
				label : "取消",
				className : "btn dark btn-outline"
			}
		}
	});
});


$(function() {
	orderManage.init();
    refundManage.init();
	//dochang1(4);

	// 高亮物流
	$(".my_wl_red").last().css("color","#FF3366");
});
